package com.meals.system.service.impl;

import com.meals.system.api.system.WhitesMealSystemGoodsAPI;
import com.meals.system.api.user.param.SaveCartItemParam;
import com.meals.system.api.user.param.UpdateCartItemParam;
import com.meals.system.api.user.vo.WhitesMealShoppingCartItemVO;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.dao.WhitesMealGoodsMapper;
import com.meals.system.dao.WhitesMealShoppingCartItemMapper;
import com.meals.system.entity.WhitesMealGoods;
import com.meals.system.entity.WhitesMealShoppingCartItem;
import com.meals.system.service.WhitesMealShoppingCartService;
import com.meals.system.util.BeanUtil;
import com.meals.system.util.PageQueryUtil;
import com.meals.system.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/11
 */
@Service
public class WhitesMealShoppingCartServiceImpl implements WhitesMealShoppingCartService {

    @Autowired
    private WhitesMealShoppingCartItemMapper whitesMealShoppingCartItemMapper;

    @Autowired
    private WhitesMealGoodsMapper whitesMealGoodsMapper;

    @Override
    public String saveWhitesMealCartItem(SaveCartItemParam saveCartItemParam, Long userId) {
        WhitesMealShoppingCartItem temp = whitesMealShoppingCartItemMapper.selectByUserIdAndGoodsId(userId, saveCartItemParam.getGoodsId());
        if (temp != null){
            // 已经存在在购物车中，则选择修改方法
            SystemException.fail(ServiceResultEnum.SHOPPING_CART_ITEM_EXIST_ERROR.getResult());
        }
        WhitesMealGoods whitesMealGoods = whitesMealGoodsMapper.selectByPrimaryKey(saveCartItemParam.getGoodsId());
        // 1、处理异常情况
        // 商品为空
        if (whitesMealGoods == null){
            return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
        }
        // 用户购物车内的商品数量
        int totalItem = whitesMealShoppingCartItemMapper.selectCountByUserId(userId);
        // 商品数量少于1
        if (saveCartItemParam.getGoodsCount() < 1){
            return ServiceResultEnum.SHOPPING_CART_ITEM_NUMBER_ERROR.getResult();
        }
        // 超出单个商品的最大数量
        if (saveCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER){
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        // 超出购物车的最大容量
        if (totalItem > Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER){
            return ServiceResultEnum.SHOPPING_CART_ITEM_TOTAL_NUMBER_ERROR.getResult();
        }
        // 2、无异常情况，进行操作
        WhitesMealShoppingCartItem whitesMealShoppingCartItem = new WhitesMealShoppingCartItem();
        BeanUtil.copyProperties(saveCartItemParam, whitesMealShoppingCartItem);
        whitesMealShoppingCartItem.setUserId(userId);
        // 设置sellerId
        whitesMealShoppingCartItem.setSellerId(whitesMealGoodsMapper.selectByPrimaryKey(saveCartItemParam.getGoodsId()).getSellerId());
        // 保存
        if (whitesMealShoppingCartItemMapper.insertSelective(whitesMealShoppingCartItem) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateWhitesMealCartItem(UpdateCartItemParam updateCartItemParam, Long userId) {
        WhitesMealShoppingCartItem whitesMealShoppingCartItemUpdate = whitesMealShoppingCartItemMapper.selectByPrimaryKey(updateCartItemParam.getCartItemId());
        // 1、处理异常情况
        // 要想更新的数据找不到
        if (whitesMealShoppingCartItemUpdate == null){
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        // 只能修改自己用户购物车的信息，不能修改别人的购物车信息
        // 当前登录账号的userId 与 要修改的cartITem中对应的userId不同，返回错误
        if (!whitesMealShoppingCartItemUpdate.getUserId().equals(userId)){
            SystemException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
            return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
        }
        // 商品数量少于1
        if (updateCartItemParam.getGoodsCount() < 1){
            return ServiceResultEnum.SHOPPING_CART_ITEM_NUMBER_ERROR.getResult();
        }
        // 超出单个商品的最大数量
        if (updateCartItemParam.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER){
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        // 数值相同，则不操作
        if (updateCartItemParam.getGoodsCount().equals(whitesMealShoppingCartItemUpdate.getGoodsCount())){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        whitesMealShoppingCartItemUpdate.setGoodsCount(updateCartItemParam.getGoodsCount());
        whitesMealShoppingCartItemUpdate.setUpdateTime(new Date());
        // 2、开始修改
        if (whitesMealShoppingCartItemMapper.updateByPrimaryKeySelective(whitesMealShoppingCartItemUpdate) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();


    }

    @Override
    public WhitesMealShoppingCartItem getWhitesMealCartItemById(Long cartItemId) {
        WhitesMealShoppingCartItem whitesMealShoppingCartItem = whitesMealShoppingCartItemMapper.selectByPrimaryKey(cartItemId);
        if (whitesMealShoppingCartItem == null){
            SystemException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        return whitesMealShoppingCartItem;
    }

    @Override
    public Boolean deleteById(Long shoppingCartItemId, Long userId) {
        WhitesMealShoppingCartItem whitesMealShoppingCartItem = whitesMealShoppingCartItemMapper.selectByPrimaryKey(userId);
        if (whitesMealShoppingCartItem == null){
            return false;
        }
        // userId不同不能删除
        if (!userId.equals(whitesMealShoppingCartItem.getUserId())){
            return false;
        }
        return whitesMealShoppingCartItemMapper.deleteByPrimaryKey(shoppingCartItemId) > 0;
    }

    /**
     * 获取我的购物车中的列表数据
     * @param userId
     * @return
     */
    @Override
    public List<WhitesMealShoppingCartItemVO> getShoppingCartItems(Long userId) {
        List<WhitesMealShoppingCartItemVO> whitesMealShoppingCartItemVOS = new ArrayList<>();
        List<WhitesMealShoppingCartItem> whitesMealShoppingCartItems = whitesMealShoppingCartItemMapper.selectByUserId(userId, Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER);

        return  getWhitesMealShoppingCartItemVOS(whitesMealShoppingCartItemVOS, whitesMealShoppingCartItems);
    }

    /**
     * 根据userId和cartItemIds获取对应的购物项记录
     * @param cartItemIds
     * @param userId
     * @return
     */
    @Override
    public List<WhitesMealShoppingCartItemVO> getCartItemsForSettle(List<Long> cartItemIds, Long userId) {
        List<WhitesMealShoppingCartItemVO> whitesMealShoppingCartItemVOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(cartItemIds)){
            SystemException.fail("购物项不能为空");
        }
        List<WhitesMealShoppingCartItem> whitesMealShoppingCartItems = whitesMealShoppingCartItemMapper.selectByUserIdAndCartItemIds(userId,cartItemIds);
        if (CollectionUtils.isEmpty(whitesMealShoppingCartItems)){
            SystemException.fail("购物项不能为空");
        }
        if (whitesMealShoppingCartItems.size() != cartItemIds.size()){
            SystemException.fail("参数异常");
        }
        return getWhitesMealShoppingCartItemVOS(whitesMealShoppingCartItemVOS, whitesMealShoppingCartItems);
    }

    @Override
    public PageResult getShoppingCartItems(PageQueryUtil pageUtil) {
        List<WhitesMealShoppingCartItemVO> whitesMealShoppingCartItemVOS = new ArrayList<>();
        List<WhitesMealShoppingCartItem> whitesMealShoppingCartItems = whitesMealShoppingCartItemMapper.findShoppingCartItems(pageUtil);
        int total = whitesMealShoppingCartItemMapper.getTotalShoppingCartItems(pageUtil);
        PageResult pageResult = new PageResult(getWhitesMealShoppingCartItemVOS(whitesMealShoppingCartItemVOS, whitesMealShoppingCartItems),total,pageUtil.getLimit(),pageUtil.getPage());
        return pageResult;
    }


    /**
     * 数据转换？
     *
     * @param whitesMealShoppingCartItemVOS
     * @param whitesMealShoppingCartItems
     * @return
     */
     private List<WhitesMealShoppingCartItemVO> getWhitesMealShoppingCartItemVOS(List<WhitesMealShoppingCartItemVO> whitesMealShoppingCartItemVOS,List<WhitesMealShoppingCartItem> whitesMealShoppingCartItems){
        if (!CollectionUtils.isEmpty(whitesMealShoppingCartItems)){
            // 查询商品信息并做数据转换
            List<Long> goodsId = whitesMealShoppingCartItems.stream().map(WhitesMealShoppingCartItem::getGoodsId).collect(Collectors.toList());
            List<WhitesMealGoods> whitesMealGoods = whitesMealGoodsMapper.selectByPrimaryKeys(goodsId);
            Map<Long, WhitesMealGoods> whitesMealGoodsMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(whitesMealGoods)){
                whitesMealGoodsMap = whitesMealGoods.stream().collect(Collectors.toMap(WhitesMealGoods::getGoodsId, Function.identity()));
            }
            for (WhitesMealShoppingCartItem whitesMealShoppingCartItem : whitesMealShoppingCartItems){
                WhitesMealShoppingCartItemVO whitesMealShoppingCartItemVO = new WhitesMealShoppingCartItemVO();
                BeanUtil.copyProperties(whitesMealShoppingCartItem, whitesMealShoppingCartItemVO);
                if (whitesMealGoodsMap.containsKey(whitesMealShoppingCartItem.getGoodsId())){
                    WhitesMealGoods whitesMealGoodsTemp = whitesMealGoodsMap.get(whitesMealShoppingCartItem.getGoodsId());
                    whitesMealShoppingCartItemVO.setGoodsCoverImg(whitesMealGoodsTemp.getGoodsCoverImg());
                    String goodsName = whitesMealGoodsTemp.getGoodsName();
                    // 字符串过长
                    if (goodsName.length() > 28){
                        goodsName = goodsName.substring(0,28) + "...";
                    }
                    whitesMealShoppingCartItemVO.setGoodsName(goodsName);
                    whitesMealShoppingCartItemVO.setSellingPrice(whitesMealGoodsTemp.getSellingPrice());
                    whitesMealShoppingCartItemVOS.add(whitesMealShoppingCartItemVO);
                }
            }
        }
        return whitesMealShoppingCartItemVOS;
     }

}
